package com.boe.hbd.client.activity;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.boe.hbd.client.Constants;
import com.boe.hbd.client.R;
import com.boe.hbd.client.domain.Comment;
import com.boe.hbd.client.domain.Landscape;
import com.boe.hbd.client.persistence.EntityManager;
import com.boe.hbd.client.service.LocationService;
import com.boe.hbd.client.service.ServiceManager;

public class LandscapeCommentActivity extends Activity implements OnClickListener {
	private EntityManager entityManager;
	private Landscape landscape = null ;
	private Comment comment = null ;
	
	public void onCreate(Bundle theInstance) {
		super.onCreate(theInstance);
		setContentView(R.layout.landscape_comment_activity);
		findViewById(R.id.saveCommentImageView).setOnClickListener(this);
		findViewById(R.id.cancelCommentImageView).setOnClickListener(this);
		entityManager = ServiceManager.getInstance(null).getService(EntityManager.class);
		
		Long landscapeId = getIntent().getExtras().getLong(Constants.KEY_LANDSCAPE_ID);
		if (landscapeId != null) {
			landscape = entityManager.getById(Landscape.class, landscapeId);
		}
		
		Long commentId   = getIntent().getExtras().getLong(Constants.KEY_COMMENT_ID);
		if (commentId != null) {
			comment = entityManager.getById(Comment.class, commentId);
			if (comment != null) {
				((EditText) findViewById(R.id.comment_description)).setText(comment.getDescription());
			}
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.cancelCommentImageView: {
				setResult(RESULT_CANCELED);
			}
			break;
			case R.id.saveCommentImageView: {
				comment = save();
				Intent intent = new Intent(this, LandscapeCommentActivity.class);
				Bundle bundle = new Bundle();
				bundle.putLong(Constants.KEY_COMMENT_ID, comment.getId());
				intent.putExtras(bundle);
				if (getParent() == null) {
				    setResult(Activity.RESULT_OK, intent);
				} else {
				    getParent().setResult(Activity.RESULT_OK, intent);
				} 
			}
			break;
		}
		finish();
	}

	private Comment save() {
		String description = ((EditText) findViewById(R.id.comment_description)).getText().toString();
		Location location = ServiceManager.getInstance(null).getService(LocationService.class).getLocation();
		if ( comment == null && location != null ) {
			comment = new Comment(landscape.getId() , location.getLatitude(), location.getLongitude(), description);
			comment.setName(description.split("\n")[0]);
			comment = entityManager.create(comment);
		} else { 
			comment.setDescription(description);
			comment.setName(description.split("\n")[0]);
			comment = entityManager.update(comment);
		}
		return comment;
	}
}